﻿@using System.Text.RegularExpressions;
@attribute [JSCustomElement("code-group")]

<MTabs @bind-Value="_tab">
    @foreach (var (tab, _) in items)
    {
        <MTab Value="tab">
            @tab
        </MTab>
    }
</MTabs>

<MTabsItems Value="_tab">
    @foreach (var (tab, content) in items)
    {
        <MTabItem Value="tab">
            <Markup Code="@content" Language="@Language" Rounded="@("sm")"></Markup>
        </MTabItem>
    }
</MTabsItems>

@code {

    [Parameter]
    public string Titles { get; set; } = default!;

    [Parameter]
    public string Items { get; set; } = default!;

    [Parameter]
    public string Language { get; set; } = default!;

    StringNumber _tab;

    List<(string title, string content)> items
    {
        get
        {
            var result = new List<(string title, string content)>();

            var titles = RegexStrToFormat(Titles, "code-group-title");
            var items = RegexStrToFormat(Items, "code-group-item");

            if (titles.Count != items.Count)
            {
                throw new ArgumentException("Tile count must be equal to Items count");
            }

            for (int i = 0; i < titles.Count; i++)
            {
                result.Add((titles[i], items[i]));
            }

            return result;
        }
    }

    List<string> RegexStrToFormat(string str, string tag)
    {
        List<string> list = new List<string>();
        string regexItem = $"<{tag}[^>]*?>(?<Text>[^<]*)</{tag}>";
        Regex regex = new Regex(regexItem, RegexOptions.IgnoreCase);
        if (regex.IsMatch(str))
        {
            MatchCollection matchCollection = regex.Matches(str);
            foreach (Match match in matchCollection)
            {
                var valueHtml = match.Value;
                valueHtml = Regex.Replace(valueHtml, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
                list.Add(valueHtml);
            }
        }

        return list;
    }
}
